package cn.stylefeng.guns.modular.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.core.common.constant.factory.PageFactory;
import cn.stylefeng.guns.core.common.page.PageInfoBT;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.core.util.ToolUtils;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.guns.core.base.tips.*;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.modular.system.model.Attachment;
import cn.stylefeng.guns.modular.system.service.IAttachmentService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.Date;
import java.util.UUID;

/**
 * 附件管理控制器
 *
 * @author fengshuonan
 * @Date 2018-12-10 16:18:24
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController extends BaseController {

    private String PREFIX = "/system/attachment/";

    @Value("${guns.file-upload-path}")
    private String fileUploadPath;

    @Autowired
    private IAttachmentService attachmentService;

    /**
     * 跳转到附件管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "attachment.html";
    }

    /**
     * 获取附件管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Attachment attachment) {
        Page<Attachment> page = new PageFactory<Attachment>().defaultPage();
        Wrapper<Attachment> wrapper = new EntityWrapper<>();
        wrapper.like(ToolUtil.isNotEmpty(attachment.getType()) && !"all".equals(attachment.getType()),
                "type", attachment.getType());
        wrapper.like(ToolUtil.isNotEmpty(attachment.getLabel()) && !"all".equals(attachment.getLabel()),
                "label", attachment.getLabel());
        wrapper.eq("create_by",ShiroKit.getUser().getAccount());
        Page<Attachment> attachmentPage = attachmentService.selectPage(page, wrapper);
        return new PageInfoBT<>(attachmentPage);
    }

    /**
     * 根据id 获取附件管理信息
     *
     * @param attachment
     * @return
     */
    @RequestMapping(value = "getAttachment")
    @ResponseBody
    public Object getAttachment(Attachment attachment) {
        attachment = attachmentService.selectById(attachment);
        return attachment;
    }

    /**
     * 添加附件
     */
    @RequestMapping(path = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object add(@RequestPart("file") MultipartFile file, Attachment attachment) {
        //原始文件名
        String originFileName = file.getOriginalFilename();
        //文件大小
        long size = file.getSize();
        //文件类型
        String contentType = file.getContentType();
        //文件扩展名
        String fileExtName = originFileName.substring(originFileName.lastIndexOf(".") + 1);
        //上传文件夹名，根据日期生成，yyyyMMdd
        String fileFolderName = DateUtil.today();
        //上传文件夹路径
        String fileFolderPath = fileUploadPath + File.separator + fileFolderName;
        //上传文件存储路径,修改存储文件名，防止重名附件
        String fileStoragePath = fileFolderPath + File.separator + UUID.randomUUID() + "." + fileExtName;
        File targetDirect = new File(fileFolderPath);
        // 判断上传目录不存在，则创建上传目录.
        if (!targetDirect.exists()) {
            targetDirect.mkdirs();
        }
        try {
            file.transferTo(new File(fileStoragePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //保存附件管理信息
        attachment.setId(UUID.randomUUID().toString().replace("-", ""));
        attachment.setName(originFileName);
        attachment.setExtName(fileExtName);
        attachment.setType(ToolUtils.fileFormat(fileExtName));
        attachment.setPath(fileStoragePath);
        ShiroUser user = ShiroKit.getUser();
        if (user != null) {
            attachment.setCreateBy(user.getAccount());
        }
        attachment.setCreateDate(new Date());
        attachmentService.insert(attachment);
        return new SuccessAbstractTip();
    }

    /**
     * 获取附件
     *
     * @param request
     * @param response
     * @param attachment
     * @throws IOException
     */
    @RequestMapping(value = "downloadFile")
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response, Attachment attachment) throws IOException {
        //如果存在id 则根据id获取附件信息
        if (ToolUtil.isNotEmpty(attachment.getId())) {
            attachment = attachmentService.selectById(attachment);
        }
        String attachPath = attachment.getPath();
        String attachName = attachment.getName();
        //上传附件本地保存路径
        File file = new File(URLDecoder.decode(attachPath, "UTF-8"));
        if (!file.exists()) {
            response.sendError(404, "文件不存在");
        }
        String showFileName = new String(attachName.getBytes("GBK"), "ISO-8859-1");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -10);
        response.addHeader("Content-Disposition", "attachment;filename=" + showFileName);
        InputStream inputStream = null;
        OutputStream os = null;
        try {
            inputStream = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 判断附件是否存在
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "isExistence")
    @ResponseBody
    public AbstractTip isExistence(HttpServletRequest request, HttpServletResponse response) {
        String fileId = request.getParameter("fileId");
        Attachment attachment = attachmentService.selectById(fileId);
        String attachPath = attachment.getPath();
        //上传附件本地保存路径
        File file = null;
        try {
            file = new File(URLDecoder.decode(attachPath, "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!file.exists()) {
            return new ErrorAbstractTip(404, "文件不存在！");
        } else {
            return new ErrorAbstractTip(200, "已存在文件！");
        }
    }

    @RequestMapping(value = "deleteFile")
    @ResponseBody
    public AbstractTip deleteFiles(String attachmentIds) {
        if (attachmentIds != null && !"".equals(attachmentIds.trim())) {
            String[] fileArr = attachmentIds.trim().split(",");
            for (String fileId : fileArr) {
                Attachment attachment = attachmentService.selectById(fileId);
                if (attachment != null && !StringUtils.isEmpty(attachment.getPath())) {
                    File file = new File(attachment.getPath());
                    file.delete();
                }
                attachmentService.deleteById(fileId);
            }
        }
        return new SuccessAbstractTip(200, "附件删除成功！");
    }

}
